//
//  WHProxyManage.m
//  WHWlproxy
//
//  Created by hyf on 2023/7/11.
//

#import "WHProxyManage.h"
#import "WHProxyInvoker.h"
#import <CommonCrypto/CommonDigest.h>

@interface WHProxyManage ()

@property (nonatomic, strong) NSMutableDictionary *invokeDict;

@end

@implementation WHProxyManage

#pragma mark - 单例模式
+ (instancetype)sharedInstance{
      static WHProxyManage *_instance;
      static dispatch_once_t onceToken;
      dispatch_once(&onceToken, ^{
          _instance = [[WHProxyManage alloc] init];
          _instance.invokeDict = [NSMutableDictionary dictionary];
    });

   return _instance;
}

-(WHProxyInvoker *)getInvokeWithConfig:(NSString*)config{
    NSString *md5Config = [WHProxyManage getmd5Str:config];
    WHProxyInvoker *tmp = self.invokeDict[md5Config];
    return tmp;
}

-(void)setInvokeWithConfig:(NSString*)config invoke:(WHProxyInvoker *)invoke{
    NSString *md5Config = [WHProxyManage getmd5Str:config];
    self.invokeDict[md5Config] = invoke;
}

-(WHProxyInvoker *)getInvokeWithRequestId:(NSString*)requestId{
    WHProxyInvoker *re = [WHProxyInvoker new];
    for (NSString *key in [self.invokeDict allKeys]) {
        WHProxyInvoker *tmp = self.invokeDict[key];
        for (NSString *tmpId in tmp.requestIdArr) {
            if([tmpId isEqualToString:requestId]){
                re = tmp;
                break;
            }
        }
    }
    return re;
}

-(void)removeNullInvoke{
    for (NSString *key in [self.invokeDict allKeys]) {
        WHProxyInvoker *tmp = self.invokeDict[key];
        if (tmp.requestIdArr.count<1) {
            if(tmp.invoker){
                NSLog(@"测试代理WLProxy---请求结束后 ： Terminate");
                tmp.invoker->Terminate();
                delete tmp.invoker;
                tmp.invoker = NULL;
                [self.invokeDict removeObjectForKey:key];
            }
        }
    }
}

-(void)removeALLInvoke{
    for (NSString *key in [self.invokeDict allKeys]) {
        WHProxyInvoker *tmp = self.invokeDict[key];
        if(tmp.invoker){
            NSLog(@"WLProxy---程序销毁时 ： Terminate");
            tmp.invoker->Terminate();
            delete tmp.invoker;
            tmp.invoker = NULL;
        }
    }
}

+ (NSString *)getmd5Str:(NSString *)str
{
    //传入参数,转化成char
    const char *cStr = [str UTF8String];
    //开辟一个16字节的空间
    unsigned char result[16];
    /*
     extern unsigned char * CC_MD5(const void *data, CC_LONG len, unsigned char *md)官方封装好的加密方法
     把str字符串转换成了32位的16进制数列（这个过程不可逆转） 存储到了md这个空间中
     */
    CC_MD5(cStr, (unsigned)strlen(cStr), result);
    return [NSString stringWithFormat:@"%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X",
             result[0], result[1], result[2], result[3],
             result[4], result[5], result[6], result[7],
             result[8], result[9], result[10], result[11],
             result[12], result[13], result[14], result[15]
             ];
}
@end
